import { ReqParams } from "@/components/common/full-table";
import { roleApi } from "@/api";
import { Icon } from "@iconify/vue";

export const useService = (
  checkedRow: Ref<Role | undefined>,
  showCreateDrawer: Function,
  showAssignModal: Function,
  getData: Function
) => {
  const getList = async (_params: ReqParams) => {
    const { status, data } = await roleApi.getList();
    if (!status) return;
    return {
      records: data,
      totalRow: data.length,
    };
  };

  const handleUpdateStatus = async (row: Role, status: boolean) => {
    const reqData: Role = { id: row.id, status };
    const { status: flag } = await roleApi.update(reqData);
    return flag;
  };

  const handlePerms = (row: Role) => {
    checkedRow.value = row;
    showAssignModal();
  };

  const handleAdd = () => {
    checkedRow.value = undefined;
    showCreateDrawer("add");
  };

  const handleEdit = (row: Role) => {
    checkedRow.value = row;
    showCreateDrawer("edit");
  };

  const handleRemove = (row: Role) => {
    const dialog = window.$dialog.error({
      title: "警告",
      content: `确定删除【${row.name}】吗？`,
      positiveText: "确定",
      negativeText: "取消",
      icon: () => <Icon icon="dashicons:warning"></Icon>,
      onPositiveClick: async () => {
        dialog.loading = true;
        try {
          const { status } = await roleApi.remove(row.id!);
          if (status) {
            window.$message.success("删除成功");
            getData();
          }
        } finally {
          dialog.loading = false;
        }
      },
    });
  };

  return {
    getList,
    handleUpdateStatus,
    handlePerms,
    handleAdd,
    handleEdit,
    handleRemove,
  };
};
